<template>
  <div class="month-electricity">
    <div class="base-background"></div>
    <div class="base-frame-img">
      <div class="box-title">
        <div class="box-t-icon"></div>
        <div class="box-t-text">本月电量明细统计</div>
      </div>
      <div class="box-content">
        <div class="m-e-box-chart" ref="chartMERef"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from "echarts";
import { getQuantityStatistics } from '@/api/homepageApi'
import { useBigScreenStore } from "@/pinia/bigScreen";
const { appContext: { config: { globalProperties } } } = getCurrentInstance()
const bsStore = useBigScreenStore();

// echarts实例
let chartMERef = ref(null);
let myChart = null;

let dayList = ref([])
let dayArrVal = ref([])
let poms = { start: '', end: '', projectIds: bsStore.projectId, isRealMeter: true, mode: '1' }
const delOption = {
  color: ['#fff', 'yellow', '#808bc6'],
  legend: { data: ['电表电量', '改造后电量'], textStyle: { color: '#fff' }, selectedMode: 'single' },
  tooltip: { trigger: 'axis' },
  grid: { left: '3%', right: '0%', bottom: '20%' },
  xAxis: {
    type: 'category',
    data: dayList.value,
    axisLabel: { show: true, color: '#0e8bff', fontSize: 13, margin: 10, showMaxLabel: true, formatter: '{value} 日' },
    axisLine: { show: true, lineStyle: { color: '#0e8bff' }, symbol: ['none', 'none'], symbolSize: [5, 5] },
    axisTick: { show: false }
  },
  yAxis: {
    type: 'value',
    name: '单位(KWH)',
    scale: true,
    axisTick: false,
    nameTextStyle: { color: '#fff', fontSize: 14, padding: [0, 0, -210, -120] },
    splitLine: { lineStyle: { color: '#0e8bff' }, show: false },
    splitArea: { show: false },
    axisLabel: { show: true, color: '#0e8bff', fontSize: '14', margin: 5 },
    axisLine: { show: true, lineStyle: { color: '#0e8bff' }, symbol: ['none', 'none'], symbolSize: [5, 5] }
  },
  toolbox: {
    show: true,
    right: '0px',
    feature: {
      dataView: { show: true, title: '下载exec文件', iconStyle: { backgroundColor: '#fff', borderColor: '#fff' }, lang: ['数据视图', '关闭', '导出Excel'] },
      magicType: { show: true, iconStyle: { backgroundColor: '#fff', borderColor: '#fff' } },
      restore: { show: true, iconStyle: { backgroundColor: '#fff', borderColor: '#fff' } },
      saveAsImage: { show: true, iconStyle: { backgroundColor: '#fff', borderColor: '#fff' } }
    }
  },
  title: { subtext: '单位(kwh)', left: 5, top: 16, subtextStyle: { color: '#0e8bff' } },
  series: [
    {
      type: 'line',
      name: '电表电量',
      barWidth: 'auto',
      data: dayArrVal.value,
      smooth: true,
      show: true,
      symbol: 'none',
      itemStyle: {
        color: '#4caf50',
        borderRadius: [5, 5, 0, 0]
      },
      areaStyle: {
        color: {
          colorStops: [
            { offset: 0, color: '#4caf50' },
            { offset: 0.5, color: '#b6e5bb4d' },
            { offset: 1, color: '#b6e5bb1a' }
          ],
          x: 0, y: 0, x2: 0, y2: 1, type: 'linear', global: false
        }
      }
    },
    {
      type: 'line',
      name: '改造后电量',
      barWidth: 'auto',
      data: dayArrVal.value,
      smooth: true,
      show: true,
      symbol: 'none',
      itemStyle: {
        color: '#198CFA',
        borderRadius: [5, 5, 0, 0]
      },
      areaStyle: {
        color: {
          colorStops: [
            { offset: 0, color: '#1877e0' },
            { offset: 0.5, color: '#b6e5bb4d' },
            { offset: 1, color: '#b6e5bb1a' }
          ],
          x: 0, y: 0, x2: 0, y2: 1, type: 'linear', global: false
        }
      }
    }
  ]
}

watch(() => bsStore.projectId, (newValue, oldValue) => {
  if (newValue === 'all') {
    getQSList(bsStore.projectIds.join(','), 'all')
  } else {
    getQSList(bsStore.projectId, 'one')
  }
})

onBeforeMount(() => { getDayNum() });

onMounted(() => {
  localStorage.setItem('chart_option_MonthElectricity', JSON.stringify(delOption))
  myChart = echarts.init(chartMERef.value);
  renderChart(delOption);
});



// 获取当月天数
const getDayNum = () => {
  const daysInMonth = globalProperties.$dayjs().endOf('month').date();
  for (let index = 0; index < daysInMonth; index++) {
    dayList.value.push(index + 1);
    dayArrVal.value.push('0')
  }
}

// 获取今年第一天的日期
const getStartTime = () => {
  return globalProperties.$dayjs().startOf('month').format("YYYY-MM-DD 00:00:00")
};

// 获取当前时间
const getEndTime = () => {
  return globalProperties.$dayjs(new Date()).format("YYYY-MM-DD HH:00:00")
};

// 数据补位(月)
const coveringNum = (data, key) => {
  let newArr = []
  if (data.length > 0) {
    const m = data[0][key].split('-')
    for (let index = 1; index < dayList.value.length + 1; index++) {
      let ym = m[0] + '-' + m[1] + '-' + (index < 10 ? '0' + index : index)
      let val = 0
      data.forEach(element => { if (element[key] === ym) { val = element.totalDiff } });
      newArr.push(val)
    }
  }
  return newArr;
}

// 获取单个项目的电量数据
const getQSList = async (ids, type) => {
  // 真实电表【绿】 理论计算【蓝】
  poms.start = getStartTime()
  poms.end = getEndTime()
  poms.projectIds = ids
  poms.isRealMeter = true
  let curOption = JSON.parse(localStorage.getItem('chart_option_MonthElectricity'))
  if (type !== 'all') {
    let oval = await getQuantityStatistics(poms)
    curOption.series = [JSON.parse(localStorage.getItem('chart_option_MonthElectricity')).series[0]]
    if (oval.data.length === 0) {
      poms.isRealMeter = false
      oval = await getQuantityStatistics(poms)
      curOption.series = [JSON.parse(localStorage.getItem('chart_option_MonthElectricity')).series[1]]
    }
    curOption.legend.data = ['能耗信息']
    curOption.series[0].name = '能耗信息'
    curOption.series[0].data = coveringNum(oval.data, '_id')
    console.log('本月数据->', curOption.series[0].data);
  } else {
    poms.isRealMeter = true
    const objval1 = await getQuantityStatistics(poms)
    curOption.series[0].data = coveringNum(objval1.data, '_id')
    poms.isRealMeter = false
    const objval2 = await getQuantityStatistics(poms)
    curOption.series[1].data = coveringNum(objval2.data, '_id')
  }
  myChart.clear()
  renderChart(curOption)
};

const renderChart = (opt) => { myChart.setOption(opt) };
</script>

<style lang="scss" scoped>
.month-electricity {
  width: 48.5%;
  margin-left: 1%;
}

.base-background {
  position: absolute;
  overflow: hidden;
  padding: 2px 1px;
  cursor: pointer;
  background-color: #003f6f;
  border-radius: 15px;
  min-width: 392px;
  opacity: 0.66;
  width: 49%;
  min-height: 200px;
  height: 17rem;
}

.base-frame-img {
  position: relative;
  margin-left: 2px;
  top: 3px;
  padding: 10px 15px 0px 15px;
  background: url(/src/assets/wbe4/zhanshic.png) center no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  min-width: 390px;
  width: 101%;
  min-height: 200px;
  height: 17rem;
}

.box-title {
  display: flex;
}

.box-t-text {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #FFFFFF;
  line-height: 32px;
  margin-left: 3px;
  user-select: none;
}

.box-t-icon {
  width: 32px;
  height: 32px;
  background: url(/src/assets/wbe4/tubiao.png) center no-repeat;
  background-size: 100% 100%;
}

.item-text {
  color: #b9ccd3;
  margin: 0.7vh 0vw;
  font-size: 12px;
}

.box-content {
  display: flex;
  justify-content: space-around;
  height: 82%;
}

.m-e-box-chart {
  width: 100%;
  height: 100%;
}
</style>